package com.marlsite.datadrivendeco.data;

import com.marlsite.datadrivendeco.DataDrivenDeco;
import com.mojang.logging.LogUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.level.storage.LevelResource;

import org.apache.commons.io.FileUtils;

import net.minecraftforge.server.ServerLifecycleHooks;

import java.util.List;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.nio.file.Path;

import org.slf4j.Logger;

public class PrimitiveDataLoader {
    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
    private static final String DATA_PATH = "data/" + DataDrivenDeco.MODID + "/primitives";
    private static List<PrimitiveDefinition> itemDefinitions = new ArrayList<PrimitiveDefinition>(); // https://stackoverflow.com/a/10400410

    private static final Logger LOGGER = LogUtils.getLogger();

    public static void loadPrimitiveDefinitions() {
        LOGGER.info("Loading primitive definitions");
        MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
        if (server != null) {
            Path datapacksDir = server.getWorldPath(LevelResource.DATAPACK_DIR);
            if (datapacksDir.toFile().exists() && datapacksDir.toFile().isDirectory()) {
                File[] datapacks = datapacksDir.toFile().listFiles();
                for (File datapack : datapacks) {
                    if (datapack.exists() && datapack.isDirectory()) {
                        Collection<File> jsonFiles = FileUtils.listFiles(new File(datapack.toString() + "/" + DATA_PATH), new String[]{"json"}, true);
                        for (File jsonFile : jsonFiles) {
                            processJsonFile(jsonFile);
                        }
                    }
                }
            }
        }
    }

    public static List<PrimitiveDefinition> getItemDefinitions() {
        return itemDefinitions;
    }

    private static void processJsonFile(File jsonFile) {
        try (FileReader reader = new FileReader(jsonFile)) {
            PrimitiveDefinition definition = GSON.fromJson(reader, PrimitiveDefinition.class);
            itemDefinitions.add(definition);
        } catch (IOException | JsonSyntaxException e) {
            e.printStackTrace();
        }
    }
}
